package com.woniuxy.user.service.impl;

import com.woniuxy.entity.Role;
import com.woniuxy.user.mapper.RoleMapper;
import com.woniuxy.user.service.RoleService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class RoleServiceImpl implements RoleService {

    @Resource
    RoleMapper roleMapper;

    @Override
    public List<Role> getAllRoles() {
        List<Role> roles = roleMapper.selectAllRoles();
        return roles;
    }

    @Override
    public Role getRole(int rid) {
        return roleMapper.selectById(rid);
    }

    @Override
    public void addRole(Role role) {
        roleMapper.insertRole(role);
    }

    @Override
    public List<Role> getRoleByName(String rolename) {
        return roleMapper.selectByName(rolename);
    }

    /**
     * 修改角色权限
     * @param rid
     * @param perms
     */
    @Override
    public void updateRoleAndPermissions(int rid, List<String> perms) {
        roleMapper.deletePermission(rid);
        perms.forEach(p->{
            if (p.endsWith("select")){
                roleMapper.insertPermission(rid,1);
            }else if (p.endsWith("insert")){
                roleMapper.insertPermission(rid,2);
            }else if (p.endsWith("update")){
                roleMapper.insertPermission(rid,3);
            }else if (p.endsWith("delete")){
                roleMapper.insertPermission(rid,4);
            }else if (p.endsWith("commit")){
                roleMapper.insertPermission(rid,6);
            }else if (p.endsWith("import")){
                roleMapper.insertPermission(rid,7);
            }else if (p.endsWith("export")){
                roleMapper.insertPermission(rid,8);
            }
        });
    }

    @Override
    public void deleteRole(int id) {
        roleMapper.deleteRole(id);
        roleMapper.deletePermission(id);
    }
}
